<template>
  <div class="hame">
    <h3 class="title">{{type === 0 ? '新增用户信息' : '修改用户信息'}}</h3>
    <div class="form-box">
      <el-form
        :model="userDetail"
        status-icon
        :rules="rules"
        ref="userForm"
        label-width="100px"
        class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userDetail.username" placeholder="用户名的长度必须大于等于4个字符，一个中文字算2个字符" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="nickname">
          <el-input v-model="userDetail.nickname" placeholder="姓名的长度必须大于等于4个字符，一个中文字算2个字符" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="telephone">
          <el-input v-model.number="userDetail.telephone" placeholder="请输入11位手机号" :disabled="true"></el-input>
        </el-form-item>
        <!-- <el-form-item label="所属部门" prop="department">
          <el-select
            ref="departmentSelect"
            :value="departmentLabels"
            multiple
            disabled
            @visible-change="showDepartmentMessage"
            @remove-tag="removeDepartmentTag"
            placeholder="请选择">
          </el-select>
        </el-form-item> -->
        <el-form-item label="用户角色">
          <div class="userRoles" @click="showRolesDialog">
            <el-tag
              v-for="(role, index) in userDetail.roles"
              :key="role.id"
              closable
              size="small"
              @close.stop="handleRoleTagRemove(index, role)"
              type="info">
              {{role.roleName}}
            </el-tag>
          </div>
          <!-- <el-select
            ref="userDetail"
            v-model="userDetail.roleNames"
            multiple
            @visible-change="showRolesDialog"
            @remove-tag="removeRoletag"
            placeholder="请选择">
          </el-select> -->
        </el-form-item>
        <!-- <el-form-item label="密码" prop="password">
          <el-input type="password" placeholder="6-16位英文、数字、下横线，区分大小写" v-model="userDetail.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" placeholder="请再次输入密码" v-model="userDetail.checkPass" autocomplete="off"></el-input>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="navToBack">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <Department ref="department" @departmentChange="departmentChange"/>
    <RoleListDialog ref="rolesDialog" :tags="userDetail.roles" @confirm="setUserRoles"/>
  </div>
</template>


<script>
import Department from './components/departments'
import RoleListDialog from './components/roleListDialog'
import Util from '@/common/util'
import { mapState } from 'vuex'

export default {
  computed: {
    departmentLabels() {
      return this.departmentNodeList.map(item => item.label)
    },
    ...mapState(['flag'])
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (!Util.FORM.isLegalPassword(value)) {
        callback(new Error('6-15位英文、数字、下横线，区分大小写'))
      } else {
        if (this.userDetail.checkPass !== '') {
          this.$refs.userForm.validateField('checkPass')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value !== this.userDetail.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const validateUserName = (rule, value, callback) => {
      if (Util.getLength(value) < 4) {
        callback(new Error('长度必须大于等于4个字符，一个中文字算2个字符'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (!Util.FORM.isLegalTel(value)) {
        callback(new Error('请输入11位手机号'))
      } else {
        callback()
      }
    }

    return {
      // type 0为添加用户
      type: 0,
      // 修改用户时存储userId
      userId: '',
      userDetail: {
        id: undefined,
        username: undefined,
        nickname: undefined,
        roles: [],
        roleNames: [],
        telephone: undefined,
        gmtCreate: undefined,
        password: undefined,
        checkPass: undefined
      },
      rules: {
        username: [
          {required: true, message: '用户名不能为空', trigger: 'blur'},
          {validator: validateUserName, trigger: 'blur'}
        ],
        name: [
          {required: true, message: '姓名不能为空', trigger: 'blur'},
          {validator: validateUserName, trigger: 'blur'}
        ],
        // phone: [
          // {required: true, message: '电话不能为空', trigger: 'blur'},
          // {validator: validatePhone, trigger: 'blur'}
        // ],
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {validator: validatePass, trigger: 'blur'}
        ],
        checkPass: [
          {validator: validatePass2, trigger: 'change'}
        ]
      },
      // 部门选中的节点
      departmentNodeList: [],
      // 角色列表
      roleList: []
    }
  },
  created() {
    const id = this.$route.params.id
    if (!!id) {
      this.type = 1
      this.userId = id
      this.queryUserData()
    }
  },
  methods: {
    queryUserData() {
      if (this.type === 0) return
      this.myGet(`/uc/user/${this.userId}`).then(data => {
        this.userDetail = {
          id: data.id,
          username: data.username,
          nickname: data.nickname,
          roles: data.roles,
          telephone: data.telephone,
          roleNames: data.roles.map(item => item.roleName),
          bizStatus: data.bizStatus,
          password: data.password,
          checkPass: data.password
        }
      }, e => this.$message(e.message))
    },
    navToBack() {
      this.$router.back()
    },
    submitForm() {
      if (this.userDetail.username === 'admin' && this.flag) {
        this.fetchData()
        return
      }
      this.$refs.userForm.validate(valid => {
        if (!valid) return
        this.fetchData()
      })
    },
    fetchData () {
      if (this.type === 0) {
        // 新建用户
        this.myPost('/uc/user', this.translateUserDetail()).then(data => {
          this.$router.back()
        }, e => this.$message(e.message))
      } else {
        // 修改用户
        this.myPut('/uc/user', this.translateUserDetail()).then(data => {
          this.$router.back()
        }, e => this.$message(e.message))
      }
    },
    showDepartmentMessage(data) {
      if (data === true) {
        const department = this.$refs.department
        department.showMessage()
        if (Array.isArray(this.departmentNodeList)) {
          department.setCheckedKeys(
            this.departmentNodeList.map(node => node.id)
          )
        } else {
          department.setCheckedKeys([])
        }
      }
    },
    removeDepartmentTag(data) {
      this.departmentNodeList = this.departmentNodeList.filter(
        item => item.label !== data
      )
    },
    departmentChange(nodeList) {
      this.departmentNodeList = nodeList
    },
    setUserRoles (roles) {
      this.userDetail.roles = roles
    },
    translateUserDetail () {
      const data = this.userDetail
      return {
        id: data.id,
        username: data.username,
        name: data.name,
        roles: data.roles.map(item => ({id: item.id})),
        phone: data.phone,
        bizStatus: data.bizStatus,
        password: data.password
      }
    },
    showRolesDialog () {
      this.$refs.rolesDialog.show()
    },
    // removeRoletag (data) {
    //   console.log(data)
    // },
    handleRoleTagRemove (i, tag) {
      this.userDetail.roles = this.userDetail.roles.filter(item => item.id !== tag.id)
    }
  },
  components: {
    Department,
    RoleListDialog
  }
}
</script>


<style>
.hame {
  background-color: #fff;
  width: 100%;
}
.title{
  font-size: 24px;
  font-weight: 400;
  color: #000;
  /* padding: 20px; */
  line-height: 2;
  margin-bottom: 30px;
  border-bottom: 1px solid rgb(131, 135, 143);
}

.form-box {
  width: 600px;
  margin: 0 auto;
}
.userRoles {
  border: 1px solid #dcdfe6;
  min-height: 40px;
}
.userRoles>.el-tag {
  margin-left: 10px;
}
</style>
